const fs = require("node:fs");
const path = require("node:path");
const http = require("node:http");
const https = require("node:https");
const url = require("node:url");
const querystring = require("node:querystring");

const hostname = "127.0.0.1";
const port = 4400;

console.log("sssssssssssssssssssssssssssssssssssssssssssssssss, preload");

// 创建代理服务器
const proxyServer = http.createServer((clientReq, clientRes) => {
  // 解析客户端请求的URL参数
  const parsedUrl = url.parse(clientReq.url, true);
  const targetUrl = parsedUrl.query.url; // 从 query 参数获取目标网站

  if (!targetUrl) {
    clientRes.writeHead(400, { "Content-Type": "text/plain" });
    clientRes.end("Missing target URL parameter: ?url=目标网站");
    return;
  }

  // 根据目标URL协议选择 http/https 模块
  const targetProtocol = targetUrl.startsWith("https") ? https : http;

  // 配置目标请求选项
  const options = {
    method: clientReq.method, // 透传请求方法（GET/POST等）
    headers: { ...clientReq.headers }, // 透传客户端原始请求头（含Cookie）
  };

  // 移除可能干扰的请求头
  delete options.headers.host; // 防止目标服务器校验Host头

  // 发起代理请求
  const proxyReq = targetProtocol.request(targetUrl, options, (proxyRes) => {
    // 复制目标服务器的响应头
    const headers = { ...proxyRes.headers };

    // 移除安全策略头
    delete headers["x-frame-options"];
    delete headers["content-security-policy"];

    // 允许跨域和凭证（关键步骤）
    headers["access-control-allow-origin"] = "*";
    headers["access-control-allow-credentials"] = "true";

    // 将处理后的响应头发送给客户端
    clientRes.writeHead(proxyRes.statusCode || 200, headers);

    // 管道传输响应内容
    proxyRes.pipe(clientRes, { end: true });
  });

  // 处理代理请求错误
  proxyReq.on("error", (err) => {
    console.error("Proxy request error:", err);
    clientRes.writeHead(500, { "Content-Type": "text/plain" });
    clientRes.end("Proxy request failed");
  });

  // 管道传输客户端请求体（用于POST/PUT等）
  clientReq.pipe(proxyReq, { end: true });
});

// 启动代理服务器
proxyServer.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

// 通过 window 对象向渲染进程注入 nodejs 能力
window.services = {
  // 读文件
  readFile(file) {
    return fs.readFileSync(file, { encoding: "utf-8" });
  },
  // 文本写入到下载目录
  writeTextFile(text) {
    const filePath = path.join(
      window.utools.getPath("downloads"),
      Date.now().toString() + ".txt"
    );
    fs.writeFileSync(filePath, text, { encoding: "utf-8" });
    return filePath;
  },
  // 图片写入到下载目录
  writeImageFile(base64Url) {
    const matchs = /^data:image\/([a-z]{1,20});base64,/i.exec(base64Url);
    if (!matchs) return;
    const filePath = path.join(
      window.utools.getPath("downloads"),
      Date.now().toString() + "." + matchs[1]
    );
    fs.writeFileSync(filePath, base64Url.substring(matchs[0].length), {
      encoding: "base64",
    });
    return filePath;
  },
};
